package meterMonitor.util;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;

import javax.mail.internet.MimeMessage;

import meterMonitor.constand.JsonFormatType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.LongSerializationPolicy;  

@Service
public class EmailBiz {

	@Autowired
	protected ResourceConfig resourceConfig; 
	
	@Autowired
	private JavaMailSenderImpl mailSender;
	@Autowired
	private TaskExecutor taskExecutor;
    
 
	//private static final AppLogger logger = AppLogger.getLog(SendingRecordBiz.class);

	private final Logger logger = LoggerFactory.getLogger(getClass());

	public void sendMail(String to, String subject, String text) {
		try {
			String[] toArry = to.split(";");
			String env;
			env = new String(resourceConfig.getValueByKey("env").getBytes("ISO8859-1"), "UTF-8");
			subject = env + "环境" + subject;
			//text = "环境：" + env + "\r\n" + text;
			SimpleMailMessage mail = new SimpleMailMessage();
			mail.setFrom(resourceConfig.getValueByKey("mail.username"));
			mail.setTo(toArry);
			mail.setSubject(subject);
			mail.setText(text);
			mailSender.send(mail);
		} catch (Exception ex) {
			logger.error("发送邮件失败"+ex.getMessage(), ex);
		}
	}

	public void sendMail(String subject, Throwable e) {
		try {
			ByteArrayOutputStream buf = new ByteArrayOutputStream();
			e.printStackTrace(new PrintWriter(buf, true));
			String expMessage = buf.toString();
			buf.close();
			this.sendMail(subject, expMessage);
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}
	}

	public void sendMail(String subject, String text) {
		try {
			String to =resourceConfig.getValueByKey("mail.toEmail");
			this.sendMail(to, subject, text);
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}
	}

	public void sendMail(String subject, String context, Throwable e) {
		try {
			ByteArrayOutputStream buf = new ByteArrayOutputStream();
			e.printStackTrace(new PrintWriter(buf, true));
			String expMessage = buf.toString();
			buf.close();
			String contextAll = "msg:\r\n" + context + "\r\n异常信息：\r\n" + expMessage;
			this.sendMail(subject, contextAll);
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}
	}
	
	public void sendMail(String subject, String context, Object request, Object response, JsonFormatType jsonFormatType) {
		try {
			String reqJson;
			String resJson;
			if(jsonFormatType.getCode().equals(JsonFormatType.JACKSON.getCode()))
			{
				 reqJson = JacksonMapper.toJson(request);
				 resJson = JacksonMapper.toJson(response);
			}
			else
			{
				Gson gson=new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss.SSS").setLongSerializationPolicy(LongSerializationPolicy.STRING).create();
				reqJson=gson.toJson(request);	
				resJson=gson.toJson(response);
			} 
		    context +=  "\r\n请求报文：\r\n" + reqJson + "\r\n响应报文：\r\n" + resJson;
			this.sendMail(subject, context);
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}
	}

	public void sendMailAsyn(final String subject, final String context, final Object request, final Object response, final JsonFormatType jsonFormatType) {
		taskExecutor.execute(new Runnable() {
			@Override
			public void run() {
				sendMail(subject, context, request, response, jsonFormatType);
			}
		});
	}
	
	public void sendMailAsyn(final String subject, final String context, final Throwable e) {
		taskExecutor.execute(new Runnable() {
			@Override
			public void run() {
				sendMail(subject, context, e);
			}
		});
	}

	public void sendMailAsyn(final String subject, final Throwable e) {
		taskExecutor.execute(new Runnable() {
			@Override
			public void run() {
				sendMail(subject, e);
			}
		});
	}

	public void sendMailAsyn(final String subject, final String context) {
		taskExecutor.execute(new Runnable() {
			@Override
			public void run() {
				sendMail(subject, context);
			}
		});
	}
	
	/**
	 * 发送报告
	 * @param to
	 * @param subject
	 * @param text
	 */
	public void sendReportMail(String to, String subject, String text) {
		try {
			SimpleMailMessage mail = new SimpleMailMessage();
			mail.setFrom(resourceConfig.getValueByKey("mail.username"));
			mail.setTo(to);
			mail.setSubject(subject);
			mail.setText(text);
			mailSender.send(mail);
		} catch (Exception ex) {
			logger.error("发送邮件失败"+ex.getMessage(), ex);
		}
	}
	
	public void sendCustomerHtmlMail(String to, String subject, String text) {
		try {
			String[] toArry = to.split(";");   
			//使用JavaMail的MimeMessage，支付更加复杂的邮件格式和内容  
			MimeMessage msg = mailSender.createMimeMessage();  
			//创建MimeMessageHelper对象，处理MimeMessage的辅助类  
			MimeMessageHelper helper = new MimeMessageHelper(msg, true,"UTF-8");  
			//使用辅助类MimeMessage设定参数  
			helper.setFrom(resourceConfig.getValueByKey("mail.username"));  
			helper.setTo(toArry);  
			helper.setSubject(subject);  
			helper.setText(text,true);  
//			//加载文件资源，作为附件  
//			ClassPathResource file = new ClassPathResource("Chrysanthemum.jpg");  
//			//加入附件  
//			helper.addAttachment("attachment.jpg", file);  
			// 发送邮件  
			mailSender.send(msg);  
		} catch (Exception ex) {
			logger.error("发送邮件失败"+ex.getMessage(), ex);
		}
	}

}
